const {userLogin,wxlogin,faceLogin}=require('../../api/login.js')
const captchaUtil = require('../../utils/captcha.js');
const menuData=require('../../utils/menu.js')
const {
    session
} = require("../../api/index.js")

Page({
    data: {
        code:'',
      selectType:[],
      showLoginRole:false,
        username: '',
        password: '',
      loginType: 0, // 默认第一个可选角色
      showRegisterPicker: false,
      isAgreed: false,
      // 新增短信登录相关数据
      loginMethod: 'account', // 登录方式：account-账号登录，sms-短信登录
      phone: '', // 手机号
      smsCode: '', // 短信验证码
      smsCountdown: 0, // 短信验证码倒计时
      phoneNumber: '', // 新增：用于存储微信获取到的手机号
      showPassword: false // 新增：密码可见性
    },

onReady(){
},
onLoad(){
    const menu=menuData.default.list()
    const selectType=["请选择登录类型"]
    wx.login({
        provider: 'weixin',
        success: function (res) {
            let code = res.code;
            if (code) {
                this.setData({
                    code
                });
            }
        }.bind(this)
    });
    menu.map((obj) => {
        if (obj["roleName"]&&obj["hasFrontLogin"]=="是") {
          selectType.push(obj["roleName"])
          this.setData({
              selectType
          })
        }
      });

      if(this.data.selectType.length<=2){
          this.setData({
            loginType:1
          })
      }

},

// 切换登录方式
switchLoginMethod(e) {
    const method = e.currentTarget.dataset.method;
    this.setData({
        loginMethod: method
    });
},

// 发送短信验证码
async sendSmsCode() {
    const phone = this.data.phone;
    
    // 验证手机号格式
    if (!phone) {
        wx.showToast({
            title: '请输入手机号',
            icon: 'none'
        });
        return;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phone)) {
        wx.showToast({
            title: '手机号格式不正确',
            icon: 'none'
        });
        return;
    }
    
    // 检查是否在倒计时中
    if (this.data.smsCountdown > 0) {
        return;
    }
    
    try {
        wx.showLoading({
            title: '发送中...'
        });
        
        // 调用发送短信验证码接口
        const res = await this.sendSmsCodeRequest(phone);
        
        wx.hideLoading();
        
        if (res.code === 0) {
            wx.showToast({
                title: '验证码已发送',
                icon: 'success'
            });
            
            // 开始倒计时
            this.startSmsCountdown();
        } else {
            wx.showToast({
                title: res.msg || '发送失败',
                icon: 'none'
            });
        }
    } catch (error) {
        wx.hideLoading();
        wx.showToast({
            title: '发送失败，请重试',
            icon: 'none'
        });
        console.error('发送短信验证码失败:', error);
    }
},

// 发送短信验证码请求
sendSmsCodeRequest(phone) {
    return new Promise((resolve, reject) => {
        const baseURL = wx.getStorageSync('baseURL') || "https://chuangyeh.zbvc-quest.com/cl29556703";
        // 使用URL查询参数的方式传递参数
        const url = baseURL + '/common/sendLoginSmsCode?mobile=' + encodeURIComponent(phone);
        wx.request({
            url: url,
            method: 'GET',
            success: (res) => {
                resolve(res.data);
            },
            fail: (err) => {
                reject(err);
            }
        });
    });
},

// 开始短信验证码倒计时
startSmsCountdown() {
    let countdown = 60; // 改为5分钟有效期
    this.setData({
        smsCountdown: countdown
    });
    
    // 记录验证码发送时间
    wx.setStorageSync('smsCodeSendTime', Date.now());
    
    const timer = setInterval(() => {
        countdown--;
        this.setData({
            smsCountdown: countdown
        });
        
        if (countdown <= 0) {
            clearInterval(timer);
        }
    }, 1000);
},

// 短信登录请求
smsLoginRequest(phone, code, role = null) {
    return new Promise((resolve, reject) => {
        const baseURL = wx.getStorageSync('baseURL') || "https://chuangyeh.zbvc-quest.com/cl29556703";
        // 构建URL查询参数
        let url = baseURL + '/common/smsLogin?phone=' + encodeURIComponent(phone) + '&code=' + encodeURIComponent(code);
        
        // 如果指定了角色，添加角色参数
        if (role) {
            url += '&role=' + encodeURIComponent(role);
        }
        
        wx.request({
            url: url,
            method: 'GET',
            success: (res) => {
                resolve(res.data);
            },
            fail: (err) => {
                reject(err);
            }
        });
    });
},

                                                                bindPickerChange: function(e) {
        this.setData({
            loginType: e.detail.value
        })

      },

    registerUser(e){
        const tablename = e.currentTarget.dataset.tablename;
        wx.navigateTo({
                     url: `../${tablename}/register`
        })
    },
  // 选择用户登录类型
  bindLoginTypeChange(e) {
    const loginType = e.detail.value;
    this.setData({
      loginType,
    });
  },
uploadAvatar() {
    wx.chooseImage({
      count: 1, // 最多可选择的图片数量
      sizeType: ['compressed'], // 选择压缩的图片
      sourceType: ['album', 'camera'], // 从相册或相机选择图片
      success: (res) => {
        const tempFilePaths = res.tempFilePaths;
        // 将选择的文件赋值给avatarUrl，并更新到页面上
        this.setData({
          avatarUrl: tempFilePaths[0]
        });
      }
    })},
    getmenuName(){
        const role = this.data.selectType[this.data.loginType]
        const menu = menuData.default.list()
        var loginRole
        menu.map(obj => {
        if (role == obj.roleName) {
        loginRole = obj.pathName
        }
        })
return loginRole
},
  async  login() {
    if (!this.data.isAgreed) {
      wx.showToast({
        title: '请先阅读并同意用户协议和隐私政策',
        icon: 'none'
      });
      return;
    }

    // 根据登录方式执行不同的登录逻辑
    if (this.data.loginMethod === 'account') {
        // 账号登录
        if (this.data.username === '') {
            wx.showToast({
              title: '请输入账号',
              icon:'none'
            });
            return;
          }
          if (this.data.password === '') {
            wx.showToast({
              title: '请输入密码',
              icon:'none'
            });
            return;
          }
            if(this.data.loginType!=0 ){
                                                                                                            var loginRole = this.getmenuName()
                const res = await userLogin(loginRole, this.data.username, this.data.password)
                    if (res.code === 0) {
                        const role = this.data.selectType[this.data.loginType]
                        // 保存登录角色
                        wx.setStorageSync('role', role)
                                                                                                    // 登录成功
                        const token = res.token;
                        wx.setStorageSync('token', token);
                        wx.setStorageSync('nowTable', loginRole);
                        // 跳转到首页或其他需要登录后才能访问的页面
                        const res2 = await session(loginRole);
                        getApp().globalData.userInfo = res2.data
                        wx.setStorageSync("nickname",this.data.username)
                        wx.setStorageSync("avatarurl", res2.data?.touxiang)
                        wx.setStorageSync("userid", res2.data?.id)
                        wx.setStorageSync("userSession", res2.data)
                        if (res2.data?.vip) {
                            wx.setStorageSync("vip", res2.data.vip);
                        }
wx.setStorageSync("avatarurl",res2.data?.touxiang)
wx.setStorageSync("avatarurl",res2.data?.touxiang)
wx.setStorageSync("avatarurl",res2.data?.touxiang)
wx.setStorageSync("avatarurl",res2.data?.touxiang)
wx.setStorageSync("avatarurl",res2.data?.touxiang)
wx.setStorageSync("avatarurl",res2.data?.touxiang)
wx.setStorageSync("avatarurl",res2.data?.touxiang)
wx.switchTab({
                          url: '/pages/index/index',
                        });
                      } else {
                        // 登录失败
                        wx.showToast({
                          title: res.msg,
                          icon:'none'
                        });
                }
              }else{
                  wx.showToast({
                    title: '请选择登陆类型',
                    icon:'none'
                  })
              }
    } else {
        // 短信登录
        if (this.data.phone === '') {
            wx.showToast({
                title: '请输入手机号',
                icon: 'none'
            });
            return;
        }
        
        if (this.data.smsCode === '') {
            wx.showToast({
                title: '请输入验证码',
                icon: 'none'
            });
            return;
        }
        
        if (!/^1[3-9]\d{9}$/.test(this.data.phone)) {
            wx.showToast({
                title: '手机号格式不正确',
                icon: 'none'
            });
            return;
        }
        
        if (!/^\d{4}$/.test(this.data.smsCode)) {
            wx.showToast({
                title: '验证码格式不正确',
                icon: 'none'
            });
            return;
        }
        
        // 检查是否选择了登录类型
        if (this.data.loginType === 0) {
            wx.showToast({
                title: '请选择登录类型',
                icon: 'none'
            });
            return;
        }
        
        // 检查验证码是否在有效期内（5分钟）
        const smsCodeSendTime = wx.getStorageSync('smsCodeSendTime');
        const currentTime = Date.now();
        const validDuration = 5 * 60 * 1000; // 5分钟
        
        if (!smsCodeSendTime || (currentTime - smsCodeSendTime) > validDuration) {
            wx.showToast({
                title: '验证码已过期，请重新获取',
                icon: 'none'
            });
            return;
        }
        
        try {
            wx.showLoading({
                title: '登录中...'
            });
            
            // 获取选择的角色
            const selectedRole = this.data.selectType[this.data.loginType];
            
            // 使用选择的角色进行登录
            const res = await this.smsLoginRequest(this.data.phone, this.data.smsCode, selectedRole);
            
            wx.hideLoading();
            
            if (res.code === 0) {
                // 登录成功
                const token = res.token;
                const role = res.role;
                const tableName = res.tableName;
                const userData = res.data;
                
                // 保存登录信息
                wx.setStorageSync('token', token);
                wx.setStorageSync('role', role);
                wx.setStorageSync('nowTable', tableName);
                wx.setStorageSync("nickname", this.data.phone);
                wx.setStorageSync("avatarurl", userData?.touxiang);
                wx.setStorageSync("userid", userData?.id);
                wx.setStorageSync("userSession", userData);
                
                if (userData?.vip) {
                    wx.setStorageSync("vip", userData.vip);
                }
                
                getApp().globalData.userInfo = userData;
                
                wx.showToast({
                    title: '登录成功',
                    icon: 'success'
                });
                
                // 跳转到首页
                wx.switchTab({
                    url: '/pages/index/index',
                });
            } else {
                wx.showToast({
                    title: res.msg || '登录失败',
                    icon: 'none'
                });
            }
        } catch (error) {
            wx.hideLoading();
            wx.showToast({
                title: '登录失败，请重试',
                icon: 'none'
            });
            console.error('短信登录失败:', error);
        }
    }
},

// 微信登录
async wxLogin() {
    if (!this.data.isAgreed) {
        wx.showToast({
            title: '请先阅读并同意用户协议和隐私政策',
            icon: 'none'
        });
        return;
    }

    // 检查是否选择了登录类型
    if (this.data.loginType === 0) {
        wx.showToast({
            title: '请选择登录类型',
            icon: 'none'
        });
        return;
    }

    try {
        wx.showLoading({
            title: '登录中...'
        });

        // 获取微信登录code
        const loginRes = await new Promise((resolve, reject) => {
            wx.login({
                provider: 'weixin',
                success: resolve,
                fail: reject
            });
        });

        if (!loginRes.code) {
            wx.hideLoading();
            wx.showToast({
                title: '微信登录失败',
                icon: 'none'
            });
            return;
        }

        // 获取用户信息
        const userInfoRes = await new Promise((resolve, reject) => {
            wx.getUserProfile({
                desc: '用于完善用户资料',
                success: resolve,
                fail: reject
            });
        });

        // 获取选择的角色
        const selectedRole = this.data.selectType[this.data.loginType];
        const loginRole = this.getmenuName();

        // 调用微信登录API
        const loginData = {
            code: loginRes.code,
            userInfo: userInfoRes.userInfo
        };

        const res = await wxlogin(loginRole, loginData);

        wx.hideLoading();

        if (res.code === 0) {
            // 登录成功
            const token = res.token;
            const role = selectedRole;
            const userData = res.data;

            // 保存登录信息
            wx.setStorageSync('token', token);
            wx.setStorageSync('role', role);
            wx.setStorageSync('nowTable', loginRole);
            wx.setStorageSync("nickname", userData?.nickname || userInfoRes.userInfo.nickName);
            wx.setStorageSync("avatarurl", userData?.touxiang || userInfoRes.userInfo.avatarUrl);
            wx.setStorageSync("userid", userData?.id);
            wx.setStorageSync("userSession", userData);

            if (userData?.vip) {
                wx.setStorageSync("vip", userData.vip);
            }

            getApp().globalData.userInfo = userData;

            wx.showToast({
                title: '登录成功',
                icon: 'success'
            });

            // 跳转到首页
            wx.switchTab({
                url: '/pages/index/index',
            });
        } else {
            wx.showToast({
                title: res.msg || '微信登录失败',
                icon: 'none'
            });
        }
    } catch (error) {
        wx.hideLoading();
        console.error('微信登录失败:', error);
        
        if (error.errMsg && error.errMsg.includes('getUserProfile:fail')) {
            wx.showToast({
                title: '需要授权用户信息才能登录',
                icon: 'none'
            });
        } else {
            wx.showToast({
                title: '微信登录失败，请重试',
                icon: 'none'
            });
        }
    }
},

  onShowRegisterPicker() {
    this.setData({ showRegisterPicker: true });
  },
  onHideRegisterPicker() {
    this.setData({ showRegisterPicker: false });
  },
  stopBubble(e) {
    // 阻止冒泡，防止点击弹窗内容关闭弹窗
    e && e.stopPropagation && e.stopPropagation();
  },
  onRegisterChuangyezhe() {
    this.setData({ showRegisterPicker: false });
    wx.navigateTo({ url: '../chuangyezhe/register' });
  },
  onRegisterDaoshi() {
    this.setData({ showRegisterPicker: false });
    wx.navigateTo({ url: '../daoshi/register' });
  },
  onAgreementChange(e) {
    this.setData({ isAgreed: !!e.detail.value.length });
  },
  onShowUserAgreement() {
    wx.navigateTo({ url: '/pages/agreement/user' }); // 你可以根据实际协议页面路径调整
  },
  onShowPrivacyPolicy() {
    wx.navigateTo({ url: '/pages/agreement/privacy' }); // 你可以根据实际协议页面路径调整
  },
  /**
   * 微信一键获取手机号
   */
  onGetPhoneNumber(e) {
    // 先校验登录类型和用户协议
    if (this.data.loginType === 0) {
      wx.showToast({
        title: '请选择登录类型',
        icon: 'none'
      });
      return;
    }
    if (!this.data.isAgreed) {
      wx.showToast({
        title: '请先阅读并同意用户协议和隐私政策',
        icon: 'none'
      });
      return;
    }
    // 只有通过校验后才执行后续逻辑
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      const { encryptedData, iv } = e.detail;
      wx.login({
        success: res => {
          wx.request({
            url: (wx.getStorageSync('baseURL') || 'https://chuangyeh.zbvc-quest.com/cl29556703') + '/common/decryptPhone',
            method: 'POST',
            data: {
              code: res.code,
              encryptedData,
              iv
            },
            success: (result) => {
              if(result.data && result.data.phoneNumber){
                // 不再setData phoneNumber
                const selectedRole = this.data.selectType[this.data.loginType];
                wx.request({
                  url: (wx.getStorageSync('baseURL') || 'https://chuangyeh.zbvc-quest.com/cl29556703') + '/common/smsLogin',
                  method: 'GET',
                  data: {
                    phone: result.data.phoneNumber,
                    code: 'WECHAT_LOGIN',
                    role: selectedRole
                  },
                  success: (loginRes) => {
                    if(loginRes.data.code === 0){
                      wx.setStorageSync('token', loginRes.data.token);
                      wx.setStorageSync('role', loginRes.data.role);
                      wx.setStorageSync('nowTable', loginRes.data.tableName);
                      wx.setStorageSync("nickname", result.data.phoneNumber);
                      wx.setStorageSync("avatarurl", loginRes.data.data?.touxiang);
                      wx.setStorageSync("userid", loginRes.data.data?.id);
                      wx.setStorageSync("userSession", loginRes.data.data);
                      if (loginRes.data.data?.vip) {
                        wx.setStorageSync("vip", loginRes.data.data.vip);
                      }
                      getApp().globalData.userInfo = loginRes.data.data;
                      wx.showToast({ title: '登录成功', icon: 'success' });
                      wx.switchTab({ url: '/pages/index/index' });
                    } else {
                      // 登录失败，判断未注册，先提示再跳转注册页面
                      const type = this.data.selectType[this.data.loginType];
                      if (type === '创业者') {
                        wx.showToast({ title: '手机号未注册此类型，请先注册', icon: 'none', duration: 2000 });
                        setTimeout(() => {
                          wx.navigateTo({ url: `/pages/chuangyezhe/register?phone=${result.data.phoneNumber}` });
                        }, 2000);
                      } else if (type === '导师') {
                        wx.showToast({ title: '手机号未注册此类型，请先注册', icon: 'none', duration: 2000 });
                        setTimeout(() => {
                          wx.navigateTo({ url: `/pages/daoshi/register?phone=${result.data.phoneNumber}` });
                        }, 2000);
                      } else {
                        wx.showToast({ title: loginRes.data.msg || '登录失败', icon: 'none' });
                      }
                    }
                  }
                });
              } else {
                wx.showToast({ title: '手机号获取失败', icon: 'none' });
              }
            },
            fail: () => {
              wx.showToast({ title: '手机号获取失败', icon: 'none' });
            }
          });
        }
      });
    } else {
      wx.showToast({ title: '用户未授权', icon: 'none' });
    }
  },
  // 密码显示/隐藏切换
  onTogglePassword() {
    this.setData({
      showPassword: !this.data.showPassword
    });
  },
  });
  